package cn.com.twoke.application.game.mario.core.ecs.util;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;

/**
 * 通用对象池实现
 *
 * @param <T> 对象类型
 */
public class ObjectPool<T> {
    private final Queue<T> pool = new ConcurrentLinkedQueue<>();
    private final Supplier<T> factory;
    private final int maxSize;
    private int createdCount = 0;

    /**
     * 构造函数
     *
     * @param factory 对象工厂函数
     * @param initialSize 初始对象数量
     * @param maxSize 最大对象数量
     */
    public ObjectPool(Supplier<T> factory, int initialSize, int maxSize) {
        this.factory = factory;
        this.maxSize = maxSize;
        
        // 预创建初始对象
        for (int i = 0; i < initialSize; i++) {
            pool.offer(factory.get());
            createdCount++;
        }
    }

    /**
     * 从对象池中获取对象
     *
     * @return 对象实例
     */
    public T acquire() {
        T object = pool.poll();
        if (object == null && createdCount < maxSize) {
            object = factory.get();
            createdCount++;
        }
        return object;
    }

    /**
     * 将对象归还到对象池
     *
     * @param object 对象实例
     */
    public void release(T object) {
        if (object != null && pool.size() < maxSize) {
            // 重置对象状态（如果对象实现了Resetable接口）
            if (object instanceof Resetable) {
                ((Resetable) object).reset();
            }
            pool.offer(object);
        }
    }

    /**
     * 获取对象池统计信息
     *
     * @return 统计信息
     */
    public String getStats() {
        return String.format("Pool Size: %d, Created: %d, Max: %d", 
            pool.size(), createdCount, maxSize);
    }

    /**
     * 重置接口
     */
    public interface Resetable {
        /**
         * 重置对象状态
         */
        void reset();
    }
}